<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>APK文件下载中心</title>
    <link rel="stylesheet" href="/css/style.css">
    <link rel="icon"
        href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>📱</text></svg>">
</head>

<body>
    <div class="app-layout">
        <!-- 侧边栏 -->
        <div class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <h3>📱 APK 管理器</h3>
            </div>
            <!-- 可滚动的内容区域 -->
            <div class="sidebar-content">
                <div id="packagerTree">
                    <div class="loading">加载中...</div>
                </div>
            </div>
        </div>

        <!-- 侧边栏切换按钮（移动端） -->
        <button class="sidebar-toggle" id="sidebarToggle">☰</button>

        <!-- 主内容区域 -->
        <div class="main-content">
            <div class="container">
                <div class="content-header">
                    <h1 id="contentTitle">🏠 项目APK概览</h1>
                    <div class="view-controls">
                        <div class="sort-control">
                            <label for="sortBy">排序：</label>
                            <select id="sortBy">
                                <option value="time_desc">时间 ↓</option>
                                <option value="time_asc">时间 ↑</option>
                                <option value="name_desc">名称 ↓</option>
                                <option value="name_asc">名称 ↑</option>
                                <option value="size_desc">大小 ↓</option>
                                <option value="size_asc">大小 ↑</option>
                            </select>
                        </div>
                        <button class="admin-link" onclick="refreshHomepage()">🔄 刷新</button>
                        <a href="/admin" class="admin-link">⚙️ 管理</a>
                    </div>
                </div>

                <div class="server-info">
                    <strong>🌐 局域网访问地址：</strong> {{SERVER_URL}}<br>
                    <strong>📁 服务器目录：</strong> {{SERVER_DIR}}<br>
                    <strong>⏰ 启动时间：</strong> {{START_TIME}}
                </div>

                <!-- 当前目录最新APK显示区域（保留但在首页隐藏） -->
                <div id="currentDirLatest" style="display: none;">
                    <div class="latest-apk-header">
                        <h3>🌟 当前目录最新版本</h3>
                    </div>
                    <div id="latestApkContent">
                        <!-- 最新APK内容将在这里显示 -->
                    </div>
                </div>

                <div id="apkContent">
                    {{CONTENT}}
                </div>

                <div class="qr-code">
                    <p>💡 提示：点击左侧侧边栏可以查看完整的文件夹结构</p>
                    <p>📱 每个项目只显示最新版本，点击"查看全部"可查看项目内所有版本</p>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentPackager = 'all';
        let currentFolder = 'all';
        let allApkData = [];
        let packagerFolders = {}; // 存储每个打包机的文件夹结构
        let packagerData = {}; // 存储打包机信息
        let expandedFolders = new Set(); // 存储展开的文件夹
        let isHomepage = true; // 标记当前是否为首页

        // 添加日志功能
        function log(message, data = null) {
            const timestamp = new Date().toLocaleTimeString();
            console.log(`[${timestamp}] ${message}`, data || '');
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function () {
            log('页面加载完成，开始初始化');
            loadPackagerTree();
            loadHomepageApks(); // 首页加载首页专用APK

            // 排序控制
            document.getElementById('sortBy').addEventListener('change', function () {
                log('排序方式改变', this.value);
                if (isHomepage) {
                    loadHomepageApks();
                } else {
                    renderApks();
                }
            });

            // 移动端侧边栏切换
            document.getElementById('sidebarToggle').addEventListener('click', function () {
                document.getElementById('sidebar').classList.toggle('mobile-open');
            });

            // 点击外部区域关闭移动端侧边栏
            document.addEventListener('click', function (e) {
                const sidebar = document.getElementById('sidebar');
                const toggle = document.getElementById('sidebarToggle');

                if (window.innerWidth <= 768 &&
                    sidebar.classList.contains('mobile-open') &&
                    !sidebar.contains(e.target) &&
                    !toggle.contains(e.target)) {
                    sidebar.classList.remove('mobile-open');
                }
            });
        });

        // 构建完整路径的辅助函数
        function buildFullPath(packagerPath, folderPath) {
            if (!folderPath) {
                return packagerPath;
            }

            // 确保packagerPath以反斜杠结尾
            const basePath = packagerPath.endsWith('\\') ? packagerPath : packagerPath + '\\';

            // 将正斜杠转换为反斜杠
            const windowsFolderPath = folderPath.replace(/\//g, '\\');

            return basePath + windowsFolderPath;
        }

        // 构建下载路径
        function buildDownloadPath(apk) {
            const downloadPath = `/download/${apk.fileId}`;
            log('构建下载路径', {
                originalPath: apk.relativePath,
                downloadPath: downloadPath,
                fullUrl: window.location.origin + downloadPath
            });
            return downloadPath;
        }

        // 加载首页APK数据
        async function loadHomepageApks() {
            try {
                log('开始加载首页APK数据');
                const response = await fetch('/api/homepage-apks');
                const result = await response.json();

                if (result.success) {
                    log('首页APK数据加载成功', {
                        count: result.data.length,
                        sample: result.data.slice(0, 2)
                    });

                    // 应用排序
                    const sortBy = document.getElementById('sortBy').value;
                    const sortedApks = sortApks(result.data, sortBy);

                    // 渲染首页内容
                    const contentHtml = generateHomepageAPKListHTML(sortedApks);
                    document.getElementById('apkContent').innerHTML = contentHtml;

                    isHomepage = true;
                } else {
                    log('首页APK数据加载失败', result);
                }
            } catch (err) {
                log('加载首页APK数据时发生错误', err);
            }
        }

        // 生成首页APK列表HTML
        function generateHomepageAPKListHTML(apkFiles) {
            if (apkFiles.length === 0) {
                return `
                <div class="no-files">
                    😅 未找到任何项目的APK文件<br>
                    请确保打包机配置正确且包含项目文件夹
                </div>`;
            }

            return `
            <div class="homepage-info">
                <p>📱 显示各项目最新版本，共 ${apkFiles.length} 个项目</p>
            </div>
            <div class="apk-grid">
                ${apkFiles.map(apk => {
                const downloadPath = buildDownloadPath(apk);
                return `
                        <div class="apk-card homepage-card">
                            <div class="project-badge">${apk.firstLevelDir}</div>
                            <div class="apk-name">📱 ${apk.name}</div>
                            <div class="apk-info">
                                📦 大小: ${apk.size}<br>
                                🕒 修改时间: ${apk.lastModified}<br>
                                📂 项目: ${apk.firstLevelDir}<br>
                                📊 项目内APK: ${apk.totalInDir} 个<br>
                                🏷️ 来源: ${apk.source || '未知'} (${apk.sourceType === 'network' ? '网络' : '本地'})
                            </div>
                            <div class="card-actions">
                                <a href="${downloadPath}" 
                                   class="download-btn latest-btn" 
                                   download="${apk.name}"
                                   title="下载 ${apk.name}">
                                    ⬇️ 下载最新版
                                </a>
                                <button class="view-all-btn" onclick="viewProjectFiles('${apk.packagerId}', '${apk.firstLevelDir}')">
                                    📋 查看全部
                                </button>
                            </div>
                        </div>
                    `;
            }).join('')}
            </div>`;
        }

        // 查看项目所有文件
        function viewProjectFiles(packagerId, projectDir) {
            log('查看项目文件', { packagerId, projectDir });

            // 在侧边栏中展开对应的打包机
            togglePackager(packagerId);

            // 选择对应的文件夹
            setTimeout(() => {
                selectFolder(packagerId, projectDir, '', projectDir);
            }, 500);
        }

        // 刷新首页
        function refreshHomepage() {
            log('刷新首页');
            loadHomepageApks();
        }

        // 加载打包机树结构
        async function loadPackagerTree() {
            try {
                log('开始加载打包机树结构');
                const response = await fetch('/api/packager-tree');
                const result = await response.json();

                if (result.success) {
                    log('打包机树结构加载成功', result.data);
                    // 存储打包机数据以便后续使用
                    result.data.forEach(packager => {
                        packagerData[packager.id] = packager;
                    });
                    renderPackagerTree(result.data);
                } else {
                    log('打包机树结构加载失败', result);
                    document.getElementById('packagerTree').innerHTML =
                        '<div style="padding: 20px; color: #f44336; text-align: center;">加载失败</div>';
                }
            } catch (err) {
                log('加载打包机树结构时发生错误', err);
                document.getElementById('packagerTree').innerHTML =
                    '<div style="padding: 20px; color: #f44336; text-align: center;">网络错误</div>';
            }
        }

        // 渲染打包机树
        function renderPackagerTree(packagers) {
            const treeHtml = packagers.map(packager => `
                <div class="packager-section">
                    <div class="packager-header" onclick="togglePackager('${packager.id}')">
                        <div class="packager-name">
                            <span>${packager.enabled ? '🟢' : '🔴'}</span>
                            <span>${packager.name}</span>
                            <span class="apk-count">${packager.totalApks}</span>
                        </div>
                        <span class="packager-toggle" id="toggle-${packager.id}">▶</span>
                    </div>
                    <div class="folder-list" id="folders-${packager.id}">
                        <div class="folder-item ${currentPackager === packager.id && currentFolder === 'all' ? 'active' : ''}" 
                             onclick="selectFolder('${packager.id}', 'all', '${packager.path}', '全部文件')">
                            <div class="folder-name">
                                <span>📁</span>
                                <span>全部文件</span>
                            </div>
                            <span class="apk-count">${packager.totalApks}</span>
                        </div>
                        <div id="tree-folders-${packager.id}">
                            <!-- 树形文件夹将在这里动态加载 -->
                        </div>
                    </div>
                </div>
            `).join('');

            document.getElementById('packagerTree').innerHTML = treeHtml ||
                '<div style="padding: 20px; color: #666; text-align: center;">暂无打包机</div>';
        }

        // 切换打包机展开/收起
        async function togglePackager(packagerId) {
            log('切换打包机展开状态', packagerId);
            const foldersDiv = document.getElementById(`folders-${packagerId}`);
            const toggleIcon = document.getElementById(`toggle-${packagerId}`);

            const isExpanding = !foldersDiv.classList.contains('expanded');

            foldersDiv.classList.toggle('expanded');
            toggleIcon.classList.toggle('expanded');

            // 如果是展开且还没有加载文件夹，则加载
            if (isExpanding && !packagerFolders[packagerId]) {
                await loadPackagerFolders(packagerId);
                renderPackagerFolders(packagerId);
            }
        }

        // 加载打包机的文件夹结构
        async function loadPackagerFolders(packagerId) {
            try {
                log('加载打包机文件夹结构', packagerId);
                const response = await fetch(`/api/packager-folders/${packagerId}`);
                const result = await response.json();

                if (result.success) {
                    log('文件夹结构加载成功', result.data);
                    packagerFolders[packagerId] = result.data;
                } else {
                    log('文件夹结构加载失败', result);
                }
            } catch (err) {
                log('加载文件夹结构时发生错误', err);
            }
        }

        // 渲染打包机的文件夹结构
        function renderPackagerFolders(packagerId) {
            const folders = packagerFolders[packagerId] || [];
            const container = document.getElementById(`tree-folders-${packagerId}`);
            const packager = packagerData[packagerId];

            const folderHtml = folders.map(folder => {
                const isExpanded = expandedFolders.has(`${packagerId}-${folder.path}`);
                const isParentExpanded = isParentFolderExpanded(packagerId, folder.path);
                const shouldShow = folder.level === 1 || isParentExpanded;

                // 使用服务器端提供的fullPath，如果没有则手动构建
                const fullPath = folder.fullPath || buildFullPath(packager.path, folder.path);

                return `
                    <div class="folder-item ${currentPackager === packagerId && currentFolder === folder.path ? 'active' : ''} ${shouldShow ? '' : 'collapsed'}" 
                         data-level="${folder.level}"
                         data-packager="${packagerId}"
                         data-path="${folder.path}"
                         onclick="selectFolder('${packagerId}', '${folder.path}', '${fullPath}', '${folder.name}')"
                         title="${fullPath}">
                        <div class="folder-name">
                            <span class="folder-expand-toggle ${folder.hasChildren ? (isExpanded ? 'expanded' : '') : ''}" 
                                  onclick="event.stopPropagation(); toggleFolderExpansion('${packagerId}', '${folder.path}')">
                                ${folder.hasChildren ? '▶' : ''}
                            </span>
                            <span>📂</span>
                            <span>${folder.name}</span>
                        </div>
                        <span class="apk-count">${folder.apkCount}</span>
                    </div>
                `;
            }).join('');

            container.innerHTML = folderHtml;
        }

        // 切换文件夹展开/收起
        function toggleFolderExpansion(packagerId, folderPath) {
            const key = `${packagerId}-${folderPath}`;

            if (expandedFolders.has(key)) {
                expandedFolders.delete(key);
            } else {
                expandedFolders.add(key);
            }

            renderPackagerFolders(packagerId);
        }

        // 检查父文件夹是否展开
        function isParentFolderExpanded(packagerId, folderPath) {
            const parts = folderPath.split('/');
            for (let i = 1; i < parts.length; i++) {
                const parentPath = parts.slice(0, i).join('/');
                const parentKey = `${packagerId}-${parentPath}`;
                if (!expandedFolders.has(parentKey)) {
                    return false;
                }
            }
            return true;
        }

        // 选择文件夹 - 切换到文件夹浏览模式
        function selectFolder(packagerId, folderPath, fullPath, folderDisplayName) {
            log('选择文件夹', { packagerId, folderPath, fullPath, folderDisplayName });

            // 切换到文件夹浏览模式
            isHomepage = false;

            currentPackager = packagerId;
            currentFolder = folderPath;

            // 更新UI状态
            document.querySelectorAll('.folder-item').forEach(item => {
                item.classList.remove('active');
            });
            event.target.closest('.folder-item').classList.add('active');

            // 更新标题 - 显示正确格式的完整路径
            let titleText;
            if (folderPath === 'all') {
                // 显示打包机的根路径
                const packager = packagerData[packagerId];
                titleText = `📁 ${packager ? packager.path : '全部文件'}`;
            } else {
                // 显示完整的文件夹路径，确保使用反斜杠
                titleText = `📁 ${fullPath}`;
            }

            document.getElementById('contentTitle').textContent = titleText;

            // 加载该文件夹的所有APK
            loadAllApks().then(() => {
                renderApks();
            });

            // 在移动端选择后自动关闭侧边栏
            if (window.innerWidth <= 768) {
                document.getElementById('sidebar').classList.remove('mobile-open');
            }
        }

        // 加载所有APK数据（文件夹浏览模式使用）
        async function loadAllApks() {
            try {
                log('开始加载所有APK数据');
                const response = await fetch('/api/apks');
                const result = await response.json();

                if (result.success) {
                    log('APK数据加载成功', {
                        count: result.data.length,
                        sample: result.data.slice(0, 2)
                    });
                    allApkData = result.data;
                } else {
                    log('APK数据加载失败', result);
                }
            } catch (err) {
                log('加载APK数据时发生错误', err);
            }
        }

        // 检查当前目录是否直接包含APK文件
        function getCurrentDirectoryApks(filteredApks) {
            // 返回当前目录下直接的APK文件（不包括子目录的）
            return filteredApks.filter(apk => {
                if (currentFolder === 'all') {
                    // 如果是"全部文件"，返回根目录下的APK
                    return !apk.folderPath || apk.folderPath === '';
                } else {
                    // 如果是特定文件夹，返回该文件夹下直接的APK
                    const apkFolderPath = (apk.folderPath || '').replace(/\\/g, '/');
                    const currentFolderPath = currentFolder.replace(/\\/g, '/');
                    return apkFolderPath === currentFolderPath;
                }
            });
        }

        // 渲染当前目录最新APK
        function renderCurrentDirectoryLatest(currentDirApks) {
            const latestSection = document.getElementById('currentDirLatest');
            const latestContent = document.getElementById('latestApkContent');

            log('渲染当前目录最新APK', { count: currentDirApks.length });

            if (currentDirApks.length === 0) {
                latestSection.style.display = 'none';
                return;
            }

            // 按时间排序，获取最新的APK
            const sortedApks = currentDirApks.sort((a, b) =>
                new Date(b.lastModifiedTime) - new Date(a.lastModifiedTime)
            );
            const latestApk = sortedApks[0];

            log('找到最新APK', latestApk);

            // 构建下载路径
            const downloadPath = buildDownloadPath(latestApk);

            // 生成最新APK的HTML
            const latestHtml = `
                <div class="latest-apk-card">
                    <div class="latest-apk-badge">最新</div>
                    <div class="latest-apk-info">
                        <div class="latest-apk-name">📱 ${latestApk.name}</div>
                        <div class="latest-apk-details">
                            📦 大小: ${latestApk.size} | 🕒 ${latestApk.lastModified} | 🏷️ ${latestApk.source}
                        </div>
                    </div>
                    <div class="latest-apk-actions">
                        <a href="${downloadPath}" 
                           class="latest-download-btn" 
                           download="${latestApk.name}"
                           title="立即下载 ${latestApk.name}">
                            ⬇️ 立即下载
                        </a>
                    </div>
                </div>
            `;

            latestContent.innerHTML = latestHtml;
            latestSection.style.display = 'block';

            log('最新APK渲染完成', { downloadPath });
        }

        // 渲染APK列表（文件夹浏览模式）
        function renderApks() {
            log('开始渲染APK列表', { currentPackager, currentFolder });

            let filteredApks = [...allApkData];

            if (currentPackager !== 'all') {
                filteredApks = filteredApks.filter(apk => apk.packagerId === currentPackager);
                log('按打包机过滤后', { count: filteredApks.length });

                if (currentFolder !== 'all') {
                    filteredApks = filteredApks.filter(apk => {
                        const apkFolderPath = (apk.folderPath || '').replace(/\\/g, '/');
                        const currentFolderPath = currentFolder.replace(/\\/g, '/');
                        return apkFolderPath === currentFolderPath;
                    });
                    log('按文件夹过滤后', { count: filteredApks.length });
                }
            }

            // 检查当前目录是否直接包含APK文件
            const currentDirApks = getCurrentDirectoryApks(filteredApks);
            log('当前目录直接包含的APK', { count: currentDirApks.length });

            // 渲染当前目录最新APK
            renderCurrentDirectoryLatest(currentDirApks);

            // 排序
            const sortBy = document.getElementById('sortBy').value;
            filteredApks = sortApks(filteredApks, sortBy);

            // 渲染所有APK列表
            const contentHtml = generateAPKListHTML(filteredApks);
            document.getElementById('apkContent').innerHTML = contentHtml;

            log('APK列表渲染完成', { totalCount: filteredApks.length });
        }

        // APK排序
        function sortApks(apks, sortBy) {
            return apks.sort((a, b) => {
                switch (sortBy) {
                    case 'time_desc':
                        return new Date(b.lastModifiedTime) - new Date(a.lastModifiedTime);
                    case 'time_asc':
                        return new Date(a.lastModifiedTime) - new Date(b.lastModifiedTime);
                    case 'name_asc':
                        return a.name.localeCompare(b.name);
                    case 'name_desc':
                        return b.name.localeCompare(a.name);
                    case 'size_desc':
                        return parseFloat(b.size) - parseFloat(a.size);
                    case 'size_asc':
                        return parseFloat(a.size) - parseFloat(b.size);
                    default:
                        return 0;
                }
            });
        }

        // 生成APK列表HTML（文件夹浏览模式）
        function generateAPKListHTML(apkFiles) {
            if (apkFiles.length === 0) {
                return `
                <div class="no-files">
                    😅 当前选择的位置没有找到APK文件<br>
                    请选择其他文件夹或检查打包机配置
                </div>`;
            }

            return `
            <div class="apk-grid">
                ${apkFiles.map(apk => {
                const downloadPath = buildDownloadPath(apk);
                return `
                        <div class="apk-card">
                            <div class="apk-name">📱 ${apk.name}</div>
                            <div class="apk-info">
                                📦 大小: ${apk.size}<br>
                                🕒 修改时间: ${apk.lastModified}<br>
                                📂 文件夹: ${apk.folderName || '根目录'}<br>
                                🏷️ 来源: ${apk.source || '未知'} (${apk.sourceType === 'network' ? '网络' : '本地'})
                            </div>
                            <a href="${downloadPath}" 
                               class="download-btn" 
                               download="${apk.name}"
                               title="下载 ${apk.name}">
                                ⬇️ 下载APK
                            </a>
                        </div>
                    `;
            }).join('')}
            </div>`;
        }
    </script>
</body>

</html>